/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.job.admin.controller;

import com.lvyh.lightframe.job.admin.annotation.PermitLimit;
import com.lvyh.lightframe.job.admin.bean.JobUserBean;
import com.lvyh.lightframe.job.Constants;
import com.lvyh.lightframe.job.enums.ErrorCode;
import com.lvyh.lightframe.job.admin.util.DateUtils;
import com.lvyh.lightframe.job.common.Result;
import com.lvyh.lightframe.job.admin.processor.JobManageProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lvyh 2021/04/11.
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private JobManageProcessor jobManageProcessor;

    @RequestMapping("")
    @PermitLimit(superAdmin = true)
    public String index(Model model) throws Exception {
        return "user/list";
    }


    @RequestMapping("/pageList")
    @PermitLimit(superAdmin = true)
    @ResponseBody
    public Map<String, Object> pageList(@RequestParam(required = false, defaultValue = "0") int start,
                                        @RequestParam(required = false, defaultValue = "10") int length,
                                        String userName) throws Exception {

        List<JobUserBean> dataList = jobManageProcessor.pageList(start, length, userName);
        dataList.forEach(p -> p.setCreateTimeText(DateUtils.format(p.getCreateTime())));
        dataList.forEach(p -> p.setUpdateTimeText(DateUtils.format(p.getUpdateTime())));

        int listCount = jobManageProcessor.pageListCount(userName);
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("data", dataList);
        maps.put("recordsTotal", listCount);        // 总记录数
        maps.put("recordsFiltered", listCount);    // 过滤后的总记录数
        return maps;
    }

    @RequestMapping("/delete")
    @PermitLimit(superAdmin = true)
    @ResponseBody
    public Result<String> delete(HttpServletRequest request, String userName) throws Exception {
        Assert.notNull(userName, "User name must not be empty.");
        JobUserBean loginUser = (JobUserBean) request.getAttribute(Constants.USER_LOGIN_KEY);
        if (loginUser.getUserName().equals(userName)) {
            return Result.create(ErrorCode.FAILED, "Current login account cannot be deleted.");
        }

        boolean result = jobManageProcessor.deleteJobUserBean(userName);
        return (result) ? Result.SUCCESS() : Result.FAILED();
    }


    @RequestMapping("/updatePwd")
    @ResponseBody
    public Result<String> updatePwd(HttpServletRequest request, String password) throws Exception {
        Assert.notNull(password, "Password must not be empty.");

        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        JobUserBean loginUser = (JobUserBean) request.getAttribute(Constants.USER_LOGIN_KEY);
        JobUserBean existUser = jobManageProcessor.getJobUserInfo(loginUser.getUserName());
        existUser.setPwd(md5Password);
        jobManageProcessor.updateJobUserBean(existUser);

        return Result.SUCCESS();
    }

}
